package com.canbot.u05.activity.presidemode;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.bean.preside.PresideTask;
import com.canbot.u05.bean.preside.PresideTaskNode;
import com.canbot.u05.control.Cmd;
import com.canbot.u05.control.RobotMgr;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.MyControlLayout;
import com.canbot.u05.view.PresideSpeedView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zmp on 2018/4/27.
 * 主持模块执行界面
 */
public class PresideTaskRunActivity extends BaseCompereActivity {


        @BindView(R.id.preside_cancel_iv)
        ImageView presideCancelIv;

        @BindView(R.id.preside_name_tv)
        TextView presideNameTv;

        @BindView(R.id.preside_run_rlv)
        RecyclerView presideRunRlv;

        @BindView(R.id.preside_play_bt)
        ImageView presidePlayBt;

        @BindView(R.id.preside_pause_bt)
        ImageView presidePauseBt;

        @BindView(R.id.preside_next_bt)
        ImageView presideNextBt;

        @BindView(R.id.control_mcl1)
        MyControlLayout controlMcl1;

        @BindView(R.id.control_mcl2)
        MyControlLayout controlMcl2;

        @BindView(R.id.preside_speed_tv)
        TextView presideSpeedTv;

        @BindView(R.id.preside_del_iv)
        ImageView presideDelIv;

        @BindView(R.id.preside_add_iv)
        ImageView presideAddIv;

        @BindView(R.id.preside_psv)
        PresideSpeedView presidePsv;

        private TextView currentSelect;

        private PresideTask presideTask;

        private List<PresideTaskNode> taskNodeList;

        private volatile int currentPosition;

        public static final int TASK_INDEX = 0;

        public static final int TASK_PAUSE = 1;

        public static final int TASK_CONTINUE = 2;

        public static final int TASK_NEXT = 3;

        public static final int TASK_STOP = 4;

        public static final int TASK_AUTO = 5;

        private short moveSpeed;

        public static final String TAG = "PresideTaskRunActivity";

        private ToastTools toastTools;

        private View ivOk;

        private View ivPb;

        private TextView tvLoad;

        private RecyclerAdapter adapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.act_hostmode_red_minute);
                EventBus.getDefault().register(this);
                toastTools = ToastTools.newInstance(this);
                ButterKnife.bind(this);
                initView();
                initData();

        }

        private void initView() {
                presidePsv.setIChooseListener(new PresideSpeedView.IChooseListener() {
                        @Override
                        public void choose(int index) {
                                setSpeed(index);
                        }
                });
        }

        /**
         * 消息发布者位置
         * ReceiveData
         * mHandler
         * case MsgType.MOBILE_PAD_MAP_TASK:
         *
         * @param bean
         */
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMapEvent(StringMsgBean bean) {
                switch (bean.getMsgType()) {
                        case MsgType.COMPERE_RAN_TASK_END:
                                toastTools.showText("主持任务结束!");
                                break;
                        case MsgType.COMPERE_RAN_TASK_STATE:
                                String msgData = bean.getMsgData();
                               // toastTools.showText("msgData:" + msgData);
                                break;
                        case MsgType.COMPERE_RAN_TASK_POSITION:
                                msgData = bean.getMsgData();
                                currentPosition = Integer.valueOf(msgData);
                                presidePauseBt.setSelected(true);
                                adapter.notifyDataSetChanged();
                                break;

                }
        }

        private void initData() {
                currentPosition = -1;
                setSpeed(1);
                String taskInfo = getIntent().getStringExtra("taskInfo");
                presideTask = JSON.parseObject(taskInfo, PresideTask.class);
                if (presideTask == null) {
                        finish();
                        return;
                }
                else {
                        taskNodeList = presideTask.getTaskNodes();
                        presideNameTv.setText(presideTask.getTaskName());
                }
                presideRunRlv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
                adapter = new RecyclerAdapter(taskNodeList);
                presideRunRlv.setAdapter(adapter);

                controlMcl1.setMyControlListener(new MyControlLayout.IMyControlListener() {
                        @Override
                        public void onDown(int index) {

                        }

                        @Override
                        public void onPress(int index) {
                                Log.e("onPress2", index + "");
                                handlerAngle(index);
                        }

                        @Override
                        public void onUp(int index, View childAt) {
                                RobotMgr.getInstance().keyControl(Cmd.Key_tingzhi);
                        }
                });

                controlMcl2.setMyControlListener(new MyControlLayout.IMyControlListener() {
                        @Override
                        public void onDown(int index) {

                        }

                        @Override
                        public void onPress(int index) {
                                Log.e("onPress2", index + "");
                                handlerHeadAngle(index);
                        }

                        @Override
                        public void onUp(int index, View childAt) {
                                RobotMgr.getInstance().keyControl(Cmd.Key_tingzhi);
                        }
                });
        }

        private void setSpeed(int index) {
                switch (index) {
                        case 0:
                                presideSpeedTv.setText("慢速");
                                moveSpeed = 300;
                                break;
                        case 1:
                                presideSpeedTv.setText("正常");
                                moveSpeed = 500;
                                break;
                        case 2:
                                presideSpeedTv.setText("快速");
                                moveSpeed = 800;
                                break;
                }

        }

        short hAngle = 0;

        short vAngle = 0;

        private void handlerHeadAngle(int index) {
                if (hAngle > 60) {
                        hAngle = 60;
                }
                else if (hAngle < -60) {
                        hAngle = -60;
                }
                if (vAngle > 30) {
                        vAngle = 30;
                }
                else if (vAngle < -30) {
                        vAngle = -30;
                }
                switch (index) {
                        case 0:
                                vAngle -= 3;
                                RobotMgr.getInstance().headControl(Cmd.Joint_Ver, (short) (vAngle));
                                break;
                        case 1:
                                hAngle += 5;
                                RobotMgr.getInstance().headControl(Cmd.Joint_Hor, (short) (-hAngle));
                                break;
                        case 2:
                                vAngle += 3;
                                RobotMgr.getInstance().headControl(Cmd.Joint_Ver, (short) (-vAngle));
                                break;
                        case 3:
                                hAngle -= 5;
                                RobotMgr.getInstance().headControl(Cmd.Joint_Hor, (short) (hAngle));
                                break;
                }
        }

        private void handlerAngle(int index) {
                switch (index) {
                        case 0:
                                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_qianjin);
                                break;
                        case 1:
                                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_youzhuan);
                                break;
                        case 2:
                                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_houtui);
                                break;
                        case 3:
                                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_zuozhuan);
                                break;
                }
        }

        @OnClick({R.id.preside_cancel_iv,
                  R.id.preside_name_tv,
                  R.id.preside_play_bt,
                  R.id.preside_pause_bt,
                  R.id.preside_add_iv,
                  R.id.preside_del_iv,
                  R.id.preside_next_bt})
        public void onViewClicked(View view) {
                switch (view.getId()) {
                        case R.id.preside_cancel_iv:
                                upTaskData(TASK_STOP, "stop");
                                break;
                        case R.id.preside_play_bt:
                                upTaskData(TASK_AUTO, view.isSelected() ? 0 : 1);
                                break;
                        case R.id.preside_pause_bt:
                                upTaskData(view.isSelected() ? TASK_PAUSE : TASK_CONTINUE, "pause_continue");
                                break;
                        case R.id.preside_next_bt:
                                upTaskData(TASK_NEXT, "next");
                                break;
                        case R.id.preside_name_tv:
                                break;
                        case R.id.preside_add_iv:
                                presidePsv.setSpeed(presidePsv.getIndex() + 1);
                                break;
                        case R.id.preside_del_iv:
                                presidePsv.setSpeed(presidePsv.getIndex() - 1);
                                break;
                }
        }

        class RecyclerAdapter extends RecyclerView.Adapter<MyHolder> {

                private final LayoutInflater layoutInflater;


                public List<PresideTaskNode> getList() {
                        return list;
                }

                private final List<PresideTaskNode> list;

                public RecyclerAdapter(List<PresideTaskNode> list) {
                        this.layoutInflater = LayoutInflater.from(PresideTaskRunActivity.this);
                        this.list = Collections.synchronizedList(list);
                }

                @Override
                public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                        View inflate = layoutInflater.inflate(R.layout.preside_run_item, parent, false);
                        return new MyHolder(inflate);
                }

                @Override
                public void onBindViewHolder(MyHolder holder, int position) {
                        holder.position = position;
                        holder.textView.setText((position + 1) + "");
                        holder.textView.setSelected(position == currentPosition);
                }

                @Override
                public int getItemCount() {
                        return list.size();
                }

                @Override
                public int getItemViewType(int position) {
                        return list.get(position).getType();
                }
        }

        class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

                public int position;

                public TextView textView;


                public MyHolder(View itemView) {
                        super(itemView);
                        textView = (TextView) itemView.findViewById(R.id.preside_run_item_tv);
                        textView.setOnClickListener(this);
                }

                @Override
                public void onClick(View v) {
                        if (currentPosition != position) {
                                upTaskData(TASK_INDEX, position);
                        }
                }
        }

        private Dialog loadDialog;

        private void showLoadDialog() {
                if (loadDialog == null) {
                        loadDialog = new Dialog(this, R.style.MyDialogStyle);
                        loadDialog.setContentView(R.layout.guide_dialog_load);
                        ivOk = loadDialog.findViewById(R.id.guide_load_iv);
                        ivPb = loadDialog.findViewById(R.id.guide_load_pb);
                        tvLoad = (TextView) loadDialog.findViewById(R.id.guide_load_tv);
                }
                ivPb.setVisibility(View.VISIBLE);
                ivOk.setVisibility(View.INVISIBLE);
                tvLoad.setText("正在加载...");
                loadDialog.setCancelable(false);
                loadDialog.show();
        }

        private void upTaskData(final int runType, final Object data) {
                showLoadDialog();
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", HostModeListViewActivity.PRESIDE_SERVLET_TYPE_TASK_RUN);
                hasMap.put("runType", runType);
                hasMap.put("data", data);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG, "onSuccess:" + result);
                                loadDialog.dismiss();
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                switch (runType) {
                                                        case TASK_INDEX:
                                                                currentPosition = Integer.valueOf(data.toString());
                                                                adapter.notifyDataSetChanged();
                                                                break;
                                                        case TASK_AUTO:
                                                                presidePlayBt.setSelected(!presidePlayBt.isSelected());
                                                                break;
                                                        case TASK_PAUSE:
                                                        case TASK_CONTINUE:
                                                                presidePauseBt.setSelected(!presidePauseBt.isSelected());
                                                                break;
                                                        case TASK_STOP:
                                                                finish();
                                                                break;
                                                }
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                toastTools.showText("服务器异常!");
                                loadDialog.dismiss();
                        }
                });
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                EventBus.getDefault().unregister(this);
        }
}
